<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/5/2 0002
 * Time: 09:22
 */
namespace app\admin\controller\system;
use app\admin\model\publicuse\PublicUse;
use app\admin\model\SystemField;
use app\admin\model\traits\TablHandle;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
/**
 * @ControllerAnnotation(title="字段管理")
 * Class Fields
 * @package app\admin\controller\system
 */
class Fields extends AdminController
{

    protected $allowModifyFields = [
        'show',
        'edit',
        'search',
        'total',
        'export',
        'status',
        'is_key',
        'xsname','required','sort',
    ];
    protected $sort = [
        'sort' => 'ASC',
        'id'   => 'DESC',
    ];
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemField();
        $array = PublicUse::getConfigDir(__CLASS__);
        $this->AllData = json_decode(file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'field'.DIRECTORY_SEPARATOR.$array['class'].'.json'),true);

    }

    public function index()
    {
        $id = request()->param('id',null);
        $field = request()->param('field',null);
        $table = request()->get('table','','trim');
        if(empty($table)){
            $this->error('参数有误');
        }
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $where[]=['table','=',$table];
//            $where = PublicUse::getParameter($where);
//            dump($where);exit;
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('parameter','?table='.$table);
        return $this->fetch();
    }
    public function add()
    {

        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            if(isset($post['is_key'])&&$post['is_key']=='on'){
                $post['is_key'] = 1;
            }else{
                $post['is_key'] = 0;
            }
//            return $this->error('创建字段失败',202,$post);
            try
            {
//    抛出异常信息和异常代码
                $bool = TablHandle::AddField($post);
            }
            catch (\Throwable $t)
            {
                $msg=$t->getMessage();
                if(strpos($msg,'Column already exists')!==false){
                    $this->error('字段名已存在');
                }else{
                    $this->error($msg);
                }

            }



            if(!$bool){
                $this->error('创建字段失败');
            }

            $post['addinput']=TablHandle::create_add_input($post);
            $post['editinput']=TablHandle::create_edit_input($post);
            $post['jscol']=TablHandle::create_js_col($post);
            $save = $this->model->save($post);
            if($save){
                Cache::clear();
                $this->success('保存成功');
            }else{
                $this->error('保存失败');
            }


        }
        $this->assignconfig('ruleLst',$this->get_rule_list());
        $data = request()->param();
        $this->assign('alldata',$this->AllData);
        $this->assign('row',$data);
        $this->assign('getTableList',$this->model->getTableList());
        return $this->fetch();
    }
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if($row['issystem']){
            $this->error('系统字段禁止修改！');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            if(isset($this->AllData['field'])&&!empty($this->AllData['field'])){
                $post = PublicUse::Conversion($post,$this->AllData['field']);
            }
            if(isset($post['is_key'])&&$post['is_key']=='on'){
                $post['is_key'] = 1;
            }else{
                $post['is_key'] = 0;
            }
            $bool = TablHandle::UpdateField($row->toArray(),$post);

            if(!$bool){
                 $this->error('修改字段失败');
            }
            try {
                $post['addinput']=TablHandle::create_add_input($post);
                $post['editinput']=TablHandle::create_edit_input($post);
                $post['jscol']=TablHandle::create_js_col($post);
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }


        $this->assignconfig('ruleLst',$this->get_rule_list($row['rule']));
        $this->assign('row', $row);
        $this->assign('alldata',$this->AllData);
        $this->assign('getTableList',$this->model->getTableList());
        return $this->fetch();
    }
    protected function get_rule_list($rule=''){
        $regexLst=config('regex');
        $ruleLst=[];
        $rule=explode(',',$rule);
        foreach ($regexLst as $k=>$v){
            if($rule && in_array($k,$rule)){
                $ruleLst[]=['name'=>$v,'value'=>$k,'selected'=>true];
            }else{
                $ruleLst[]=['name'=>$v,'value'=>$k];
            }

        }
        return $ruleLst;
    }
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $bool = TablHandle::DeleteField($row->toArray());
        if(!$bool){
            return $this->error('删除字段失败');
        }
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $this->checkPostRequest();
        $post = $this->request->post();
        $rule = [
            'id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);

        $row = $this->model->find($post['id']);
        if (!$row) {
            $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
//        $data=[];
        $row[$post['field']]= $post['value'];
        if($post['field']=='required' && $post['value']==1){
            $row['show']=1;
            $row['edit']=1;
        }
        if($post['field']=='search' || $post['field']=='show'){
            $row['jscol']=TablHandle::create_js_col($row);
        }elseif($post['field']=='xsname'){
//                说明改的是显示名称则更新对应的模板数据
            $row['addinput']=TablHandle::create_add_input($row);
            $row['editinput']=TablHandle::create_edit_input($row);
            $row['jscol']=TablHandle::create_js_col($row);
        }elseif($post['field']=='required'){
            $row['addinput']=TablHandle::create_add_input($row);
            $row['editinput']=TablHandle::create_edit_input($row);
        }
        $row->save();
        $this->success('保存成功');
    }
}